<template>
  <div class="answers-section">
    <div class="answers-header">
      <h3 class="answers-title"><t-icon name="chat" /> 回答 ({{ answers.length }})</h3>
      
      <div class="sort-switch">
        <span :class="{ active: !answerSortDesc }" @click="answerSortDesc = false; handleSortChange()">最早</span>
        <span :class="{ active: answerSortDesc }" @click="answerSortDesc = true; handleSortChange()">最新</span>
      </div>
    </div>

    <div id="answers-container" v-if="answers.length > 0">
      <div v-for="answer in answers" :key="answer.id" class="answer-item">
        <div class="answer-content" v-html="answer.content"></div>
        <div class="answer-footer">
          <div class="time">{{ formatDate(answer.createdAt) }}</div>
          <div class="answer-actions">
            <button class="action-button" :disabled="answer.isLiking" @click="handleAnswerLike(answer)">
              <t-icon 
                name="thumb-up" 
                :class="{ active: answer.isLiked }" 
                v-if="!answer.isLiking"
              />
              <t-icon name="loading" spin v-if="answer.isLiking" />
              <span>{{ answer.likeCount || 0 }}</span>
            </button>
            <button class="action-button" @click="toggleComments(answer)">
              <t-icon name="chat" />
              <span>评论 ({{ answer.commentCount || 0 }})</span>
            </button>
          </div>
        </div>

        <!-- 评论区 -->
        <div class="comments-section" v-if="answer.showComments">
          <div class="editor-container">
            <div class="editor-wrapper">
              <Toolbar
                style="border-bottom: 1px solid #dcdfe6"
                :editor="editorRef"
                :defaultConfig="toolbarConfig"
                :mode="mode"
              />
              <Editor
                style="height: 200px; overflow-y: hidden;"
                v-model="answer.newComment"
                :defaultConfig="editorConfig"
                :mode="mode"
                @onCreated="handleCreated"
              />
            </div>
            <button class="submit-comment" @click="submitComment(answer)">
              <t-icon name="send" /> 发表评论
            </button>
          </div>

          <div class="comments-list" v-if="answer.comments && answer.comments.length > 0">
            <div v-for="comment in answer.comments" :key="comment.id" class="comment-item">
              <div class="comment-content" v-html="comment.content"></div>
              <div class="comment-footer">
                <div class="time">{{ formatDate(comment.createdAt) }}</div>
                <div class="comment-actions">
                  <button class="action-button" :disabled="comment.isLiking" @click="handleCommentLike(comment)">
                    <t-icon 
                      name="thumb-up" 
                      :class="{ active: comment.isLiked }" 
                      v-if="!comment.isLiking"
                    />
                    <t-icon name="loading" spin v-if="comment.isLiking" />
                    <span>{{ comment.likeCount || 0 }}</span>
                  </button>
                </div>
              </div>
            </div>
          </div>
          <div v-else class="no-comments">
            <p>暂无评论，来发表第一条评论吧！</p>
          </div>
        </div>
      </div>
    </div>
    <div v-else class="no-answers">
      <p>暂无回答</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import '@wangeditor/editor/dist/css/style.css';
import { uploadImage } from '@/api/uploadApi';
import { ElMessage } from 'element-plus';
import { useRoute } from 'vue-router';
import { getAllAnswersByQuestionIdASC, getAllAnswersByQuestionIdDESC } from '@/api/answerApi';

const route = useRoute();
const questionId = route.path.split('/').slice(-2)[0];

const answers = ref([]);
const answerSortDesc = ref(false);

// 编辑器配置
const toolbarConfig = {
  toolbarKeys: [
    'bold',
    'italic',
    'underline',
    'through',
    'color',
    'bgColor',
    'fontSize',
    'fontFamily',
    'bulletedList',
    'numberedList',
    'justifyLeft',
    'justifyCenter',
    'justifyRight',
    'emotion',
    'uploadImage',
    'undo',
    'redo'
  ]
};

const editorConfig = {
  placeholder: '写下你的评论...',
  autoFocus: false,
  MENU_CONF: {
    uploadImage: {
      customUpload: async (file, insertFn) => {
        const formData = new FormData();
        formData.append('file', file);

        try {
          const response = await uploadImage(formData);
          insertFn(response.data.url);
          ElMessage({
            message: "图片上传成功",
            type: 'success',
          });
        } catch (error) {
          console.error('图片上传出错:', error);
          ElMessage({
            message: "图片上传出错",
            type: 'error',
          });
        }
      }
    }
  }
};

const mode = 'default';

const handleCreated = (editor) => {
  editorRef.value = editor;
};

const formatDate = (date) => {
  if (!date) return '';
  return new Date(date).toLocaleString();
};

const toggleComments = (answer) => {
  answer.showComments = !answer.showComments;
  if (answer.showComments && !answer.comments) {
    answer.comments = [];
    // 这里可以加载评论数据
  }
};

const handleSortChange = async () => {
  try {
    const response = await (answerSortDesc.value ? 
      getAllAnswersByQuestionIdDESC(questionId, 1, 10) : 
      getAllAnswersByQuestionIdASC(questionId, 1, 10));
    answers.value = response.data;
  } catch (error) {
    console.error('获取回答列表失败:', error);
    ElMessage.error('获取回答列表失败');
  }
};

const handleAnswerLike = async (answer) => {
  answer.isLiking = true;
  try {
    // 处理点赞逻辑
    answer.isLiked = !answer.isLiked;
    answer.likeCount += answer.isLiked ? 1 : -1;
  } catch (error) {
    console.error('点赞失败:', error);
  } finally {
    answer.isLiking = false;
  }
};

const handleCommentLike = async (comment) => {
  comment.isLiking = true;
  try {
    // 处理评论点赞逻辑
    comment.isLiked = !comment.isLiked;
    comment.likeCount += comment.isLiked ? 1 : -1;
  } catch (error) {
    console.error('评论点赞失败:', error);
  } finally {
    comment.isLiking = false;
  }
};

const submitComment = async (answer) => {
  if (!answer.newComment) {
    ElMessage.warning('评论内容不能为空');
    return;
  }

  try {
    // 提交评论逻辑
    const newComment = {
      id: Date.now().toString(),
      content: answer.newComment,
      createdAt: new Date(),
      likeCount: 0,
      isLiked: false
    };
    
    if (!answer.comments) {
      answer.comments = [];
    }
    answer.comments.push(newComment);
    answer.commentCount = (answer.commentCount || 0) + 1;
    answer.newComment = '';
    
    ElMessage.success('评论发表成功');
  } catch (error) {
    console.error('评论发表失败:', error);
    ElMessage.error('评论发表失败');
  }
};

onMounted(async () => {
  await handleSortChange();
});
</script>

<style scoped>
.answers-section {
  margin-top: 40px;
}

.answers-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.answers-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
}

.answer-item {
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 10px;
  background-color: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
}

.answer-item:hover {
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.answer-content {
  margin-bottom: 15px;
}

.answer-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.answer-actions {
  display: flex;
  gap: 20px;
}

.action-button {
  display: flex;
  align-items: center;
  gap: 8px;
  background: none;
  border: none;
  cursor: pointer;
  color: #606266;
  transition: all 0.3s;
}

.action-button:hover {
  color: #409eff;
}

.action-button .t-icon.active {
  color: #409eff;
}

.comments-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.editor-container {
  margin-bottom: 20px;
}

.submit-comment {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  width: 100%;
  padding: 12px;
  background-color: #409EFF;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.submit-comment:hover {
  background-color: #337ecc;
}

.no-answers, .no-comments {
  text-align: center;
  padding: 20px;
  color: #909399;
}

.sort-switch {
  display: flex;
  gap: 10px;
}

.sort-switch span {
  cursor: pointer;
  padding: 2px 8px;
  border-radius: 4px;
  transition: all 0.3s;
}

.sort-switch span.active {
  background-color: #409eff;
  color: white;
}

.sort-switch span:hover {
  background-color: #e4f0ff;
}

.time {
  color: #909399;
  font-size: 0.9em;
}
</style>
